package com.fanghuyun.iswaf.function;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.fanghuyun.iswaf.common.ClientLogger;
import com.fanghuyun.iswaf.common.Constants;
import com.fanghuyun.iswaf.filter.DoFilter;
import com.fanghuyun.iswaf.util.StringUtil;


public class SqlInject extends DoFilter{
	
	private static Logger logger = Logger.getLogger("iswaf");
	
	public static String getAsciiEncoding(String str,String key){
		for(String s:key.split(",")){
			str = str.replaceAll("(?i)("+s+")", s.replace(""+s.charAt(0), "&#"+(int)s.charAt(0)+";"));
		}
		return str;
	}
	
	public static boolean isSqlInject(String content,Properties properties) throws Exception{
		try {
			String sql = properties.getProperty("function.sql");
			List<String> ls = new ArrayList<String>();
			for(String s:sql.split(",")){
				String v = properties.getProperty("function.sql."+s);
				if(v!=null){
					ls.add("("+s+".+("+v+"))");
				}
			}
			return Pattern.compile(StringUtils.join(ls,"|"),Pattern.DOTALL|Pattern.CASE_INSENSITIVE).matcher(content).find();
		} catch (Exception e) {
			throw e;
		}
	}

	public static Map<String, Object> checkInject(HttpServletRequest request,Map<String, Object> wrapper,Properties properties){
		try {
			Enumeration<?> e = request.getParameterNames();
			while (e.hasMoreElements()) {
				String key = (String)e.nextElement();
				String value = request.getParameter(key);
				if(value!=null||!"".equals(value)){
					if(isSqlInject(value,properties)){
						ClientLogger.addAttackLogs(request,Constants.SYS_FUNCTION_SQLINJECT);
						wrapper.put(key, getAsciiEncoding(value,properties.getProperty("function.sql")));
						return wrapper;
					}
				}
			}
			Cookie[] c = request.getCookies();
			if(StringUtil.isNotEmpty(c)){
				for (int i = 0; i < c.length; i++) {
					Cookie cookie = c[i];
					String value = cookie.getValue();
					if(value!=null||!"".equals(value)){
						if(isSqlInject(value,properties)){
							ClientLogger.addAttackLogs(request,Constants.SYS_FUNCTION_SQLINJECT);
							cookie.setValue(getAsciiEncoding(value,properties.getProperty("function.sql")));
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return wrapper;
	}
	
}
